﻿using System; 
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic; 
using System.Data;
using TimeTravel.Commons;
using TimeTravel.Components;
using TimeTravel.Extentions;
using TimeTravel.IData;

namespace TimeTravel.SqlServer  
{
    public class SysUserData : ISysUserData
    {
        #region Fields

        private static readonly SqlHelper DbHelper = new SqlHelper();
        private static readonly string[] V_Columns = { "[id]", "[title]", "[mail_title]", "[mail_body]" };

        #endregion

        #region Implementation of IDataBase<SysUserInfo>

        /// <summary>
        /// 添加记录
        /// </summary>
        public int Add(SysUserInfo sysUser)
        {
            if (sysUser == null) return 0;
            sysUser.Salt = StringHelper.GetGuidString();
            sysUser.Password = CryptoHelper.MD5Encrypt(sysUser.Password + sysUser.Salt);
            var strSql = new StringBuilder();
            strSql.Append("insert into SysUser(");
            strSql.Append("[username],[userpwd],[headpic],[nickname],[lastlogin],[registertime],[salt],[email])");
            strSql.Append(" values ");
            strSql.Append("(@username,@userpwd,@headpic,@nickname,@lastlogin,@registertime,@salt,@email);");
            strSql.Append("select @@IDENTITY ;");
            
            SqlParameter[] parameters = {
                                            new SqlParameter("@username", SqlDbType.NVarChar, 50),
                                            new SqlParameter("@userpwd", SqlDbType.NVarChar, 50),
                                            new SqlParameter("@headpic", SqlDbType.NVarChar, 50),
                                            new SqlParameter("@nickname", SqlDbType.NVarChar, 50),
                                            new SqlParameter("@salt", SqlDbType.NVarChar, 100),
                                            new SqlParameter("@lastlogin", SqlDbType.Int),
                                            new SqlParameter("@registertime", SqlDbType.Int),
                                            new SqlParameter("@email", SqlDbType.NVarChar,50)
                                        };
            parameters[0].Value = sysUser.Name;
            parameters[1].Value = sysUser.Password;
            parameters[2].Value = sysUser.Picture;
            parameters[3].Value = sysUser.NickName;
            parameters[4].Value = sysUser.Salt;
            parameters[5].Value = sysUser.LastLogin;
            parameters[6].Value = sysUser.RegisterTime;
            parameters[7].Value = sysUser.Email;

            var result = DbHelper.ExecuteScalar(CommandType.Text, strSql.ToString(), parameters);
            return result == null ? 0 : Convert.ToInt32(result);
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            //TODO:删除用户时，需要连带删除用户关联的所有资源。对于管理员，有公告，新闻，操作日志等。
            throw new NotImplementedException();
        }

        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="sysUser"></param>
        public void Update(SysUserInfo sysUser)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public IList<SysUserInfo> GetAll()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 根据条件获取
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RecordSet<SysUserInfo> GetBySearch(PageQueryInfo query)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysUserInfo GetOne(int id)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns></returns>
        public int GetTotalCount()
        {
            var strSql = new StringBuilder();
            strSql.Append("select count(id) from SysUser ");
            strSql.Append("where DeleteFlag = 0;");
            var result = DbHelper.ExecuteScalar(CommandType.Text, strSql.ToString());
            return result == null ? 0 : Convert.ToInt32(result);
        }

        /// <summary>
        /// 检测用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public SysUserInfo CheckLogin(string username, string password)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                return null;
            }
            var strSql = new StringBuilder();
            strSql.AppendFormat("select {0} from SysUser ",String.Join(",",V_Columns));
            strSql.Append(" where username = @username and DeleteFlag = 0;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@username", SqlDbType.NVarChar, 50, username)
                                        };
            var resultObj = DbHelper.ExecuteObject(CommandType.Text, strSql.ToString(), DataReaderParser, parameters);
            if (resultObj == null)
            {
                return null;
            }
            var passwordAndSaltEncryptStr = CryptoHelper.MD5Encrypt(password + resultObj.Salt);
            if (passwordAndSaltEncryptStr.Equals(resultObj.Password))
            {
                //更新用户登录时间及变更Salt值
                resultObj.LastLogin = DateHelper.GetTimeStampFromDate(DateTime.Now);
                resultObj.Salt = StringHelper.GetGuidString();
                resultObj.Password = CryptoHelper.MD5Encrypt(password + resultObj.Salt);
                Update(resultObj);
                return resultObj;
            }
            return null;
        }

        #endregion

        #region BuildNavMenuObject

        /// <summary>
        /// 从DataReader中构建对象
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private SysUserInfo DataReaderParser(IDataReader reader)
        {
            var sysUser = new SysUserInfo();
            
            return sysUser;
        }

        #endregion
    }
}

